package com.threedt.nova.portfolio.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.threedt.nova.portfolio.domain.User;
import com.threedt.nova.portfolio.service.UserServices;

public class UserAction implements Serializable {
	private User user = new User();
	private List<User> users = new ArrayList<User>();

	@Autowired(required = true)
	private UserServices userServices;

	public UserServices getUserServices() {
		return userServices;
	}

	public void setUserServices(UserServices userServices) {
		this.userServices = userServices;
	}

	public void cereate() {
		System.out.println("This is create method ..............");
	}

	public String login() {

		String result = "fail";

		System.out.println("The user name is " + user.getUserName());

		User thisUser = userServices.fetchUser(user);
		if (thisUser != null) {
			users = userServices.fetchAllUsers();
			return "success";

		} else {
			FacesMessage fm = new FacesMessage("login fail");
			FacesContext.getCurrentInstance().addMessage("login fail", fm);
			System.out.println("the login fail");
			return null;
		}

	}

	public String addUser() {

		User thisuser = userServices.saveOrUpdateUsers(user);

		if (thisuser != null) {
			users = userServices.fetchAllUsers();
			return "success";
		} else {
			return "fail";
		}
	}

	public String editUser() {

		System.out.println("User name " + user.getUserName());

		boolean result = userServices.deleteUsers(user);
		User thisuser = userServices.saveOrUpdateUsers(user);

		if (thisuser != null) {
			users = userServices.fetchAllUsers();
			return "success";
		} else {
			return "fail";
		}
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}
}
